package com.zoo.web.action;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.zoo.common.CarBean;
import com.zoo.entity.Product;

@Controller
@Scope("prototype")
public class ShopCarAction {
	@Resource
	private CarBean carBean ;
	
	private Product product ;
	
	private Double total = 0.0 ;

	public Double getTotal() {
		return total;
	}

	public void setTotal(Double total) {
		this.total = total;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	/**
     * 把商品加入购物车
     * @return
     */
    @SuppressWarnings("unchecked")
	public String addToCar(){
		Map<String, CarBean> car = (Map<String, CarBean>) ActionContext.getContext().getSession().get("car");
		car = carBean.addToCar(String.valueOf(product.getId()), car);
		if(car!=null){				
			for(String key : car.keySet()){
				CarBean cb = car.get(key);
				total = total + cb.getCount();
			}
		}
		ActionContext.getContext().getSession().put("car", car);
		ActionContext.getContext().getSession().put("total", total);
    	return "view" ;
    }
    
    /**
     * 查看购物车
     * @return
     */
    public String viewCar(){
    	return "view" ;
    }
    
    /**
     * 清空购物车
     * @return
     */
    public String clean(){
    	ActionContext.getContext().getSession().remove("car");
    	ActionContext.getContext().getSession().remove("total");
    	return "view" ;
    }

    /**
     * 从购物车删除商品
     * @return
     */
    @SuppressWarnings("unchecked")
	public String delFromCar(){
    	Map<String, CarBean> car = (Map<String, CarBean>) ActionContext.getContext().getSession().get("car");
		if(car!=null){	
			car.remove(String.valueOf(product.getId()));
			for(String key : car.keySet()){
				CarBean cb = car.get(key);
				total = total + cb.getCount();
			}
		}
		ActionContext.getContext().getSession().put("car", car);
		ActionContext.getContext().getSession().put("total", total);
    	return "view" ;
    }
}
